package mp

import (
	"context"
	"errors"

	_ "github.com/go-sql-driver/mysql"
	"github.com/zeromicro/go-zero/core/logx"
	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	"ruikc.com/server/utils"
	xb "xorm.io/builder"
)

type DeptSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeptSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeptSaveLogic {
	return &DeptSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeptSaveLogic) DeptSave(req *types.DeptReq) (string, error) {
	level := 1
	tier := ",0,"
	if req.Pid != 0 {
		pData := &models.Dept{
			Id: req.Pid,
		}
		has := db.GetData(pData)
		if !has {
			return "", errors.New("上层部门不存在或已经删除")
		}
		level = pData.Level + 1
		tier = pData.Tier + utils.IntToString(pData.Id) + ","
	}
	data := &models.Dept{
		Level: level,
		Tier:  tier,
		Title: req.Title,
		Pid:   req.Pid,
	}

	if req.Id == 0 {
		db.InsertData(data)
	} else {
		db.UpdateData(data, xb.Eq{"id": req.Id})
	}

	return "操作成功", nil
}
